#include "data.h"
#include "Log.h"
#include <string>
#include "safe_time.h"
using namespace std;

int database_bdb::get_data(int subclass_id, int b2c_flag, feature_t feat_type, int vid_num, int *vid_list, vid_data *datas)
{
	int num = 0;
    int class_id = 1;
	feature_db *db = find_feature_db(class_id, subclass_id, b2c_flag, feat_type);
	if (!db)
		return -1;
	timeval begin, end;
	safe_gettimeofday(&begin, 0);
	for (int i = 0; i != vid_num; i++) {
		if (db->get_vid_data(vid_list[i], datas[i].data, datas[i].length) == 0)
			num++;
	}
	safe_gettimeofday(&end, 0);
	LOG_DEBUG_VA("%s get data, vid num:%d, time:%d us", feat_type == database::lf ? "lf" : (feat_type == database::gf ? "gf" : "tv")
	, vid_num , (end.tv_sec - begin.tv_sec) * 1000000 + (end.tv_usec - begin.tv_usec));
	int nbytes = 0;
	for (int i = 0; i != vid_num; i++) {
		nbytes += datas[i].length;
		//LOG_DEBUG_VA("[bdb] vid[%d]:%d, length:%d", i, vid_list[i], datas[i].length);
	}
	LOG_DEBUG_VA("[bdb] total bytes:%d", nbytes);
	
	return num;
}

feature_db *database_bdb::find_feature_db(int class_id, int subclass_id, int b2c_flag, feature_t feat_type)
{
	map_key mk;
	mk.class_id = class_id;
	mk.subclass_id = subclass_id;
	mk.b2c_flag = b2c_flag;
	mk.feat_type = feat_type;
	
	if (_feature_db_map.find(mk) != _feature_db_map.end())
		return _feature_db_map.find(mk)->second;

	string db_path = get_db_path(class_id, subclass_id, b2c_flag, feat_type);
	feature_db *db = new feature_db();
	//set cache to 5GB
	//db->set_cachesize(1024*1024*1024*1);
	if (!(db->open(db_path, feature_db::read))) {
		delete db;
		return 0;
	}
	_feature_db_map.insert(pair<map_key, feature_db*>(mk, db));
	return db;
}

string database_bdb::get_db_path(int class_id, int subclass_id, int b2c_flag, feature_t feat_type)
{
	char path_buf[512];
	char feat[3];
	switch (feat_type) {
	case lf: memcpy(feat,"lf",3); break;
	case gf: memcpy(feat,"gf",3); break;
	case tv: memcpy(feat,"tv",3); break;
	}
	snprintf(path_buf, 511, "%s/taobao/%d/%s/data.db", _data_root_path.c_str(), subclass_id, feat);
	string ret = path_buf;
	return ret;
}

